//
//  UserHeaderCell.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/7.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Kingfisher

class UserHeaderCell: UITableViewCell {
    
    var panel = UIView()
    
    var avatarImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.isUserInteractionEnabled = true
        imageView.contentMode = .scaleAspectFill
        imageView.image = UIImage(named: "")
        imageView.layer.cornerRadius = 35
        imageView.layer.masksToBounds = true
        return imageView
    }()
    
    lazy var stateImage:UIImageView = {
        let stateImage = UIImageView.init()
        stateImage.image = UIImage(named: "reth_sucess")
        stateImage.isHidden = true
        return stateImage
    }()
    var usernameLabel: UILabel = {
        let label = UILabel()
        label.text = ""
        label.font = UIFont.boldSystemFont(ofSize: 20)
        
        return label
    }()
    
    var avatarChangeHandler:(() -> Void)?

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.avatarImageView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doTapAvatarAction)))
        
        self.setupViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupViews() {
        self.backgroundColor = UIColor.clear
        self.panel.backgroundColor = UIColor.white
        self.contentView.addSubview(self.panel)
        self.panel.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self.contentView)
        make.bottom.equalTo(self.contentView).offset(-10)
        }
        
        self.panel.addSubview(self.avatarImageView)
        self.avatarImageView.snp.makeConstraints { (make) in
            make.top.equalTo(self.panel).offset(10)
            make.left.equalTo(self.panel).offset(25)
            make.bottom.equalTo(self.panel).offset(-10)
            make.width.equalTo(self.avatarImageView.snp.height)
        }
        
        self.panel.addSubview(self.usernameLabel)
        self.usernameLabel.snp.makeConstraints { (make) in
        make.left.equalTo(self.avatarImageView.snp.right).offset(25)
            make.centerY.equalTo(self.avatarImageView)
        }
        self.panel.addSubview(self.stateImage)
        self.stateImage.snp.makeConstraints { (make) in
            make.top.equalTo(self.panel).offset(15)
            make.right.equalTo(self.panel).offset(-20)
            make.size.equalTo(CGSize(width: 47, height: 16))
        }
    }
    
    func doTapAvatarAction() {
        var responder = self.next
        while !(responder is UIViewController) {
            responder = responder?.next
        }
        if responder is UIViewController {
            let vc = responder as! UIViewController
            
            let tool = PhotoSheet()
            tool.showPhotoSheet(viewController: vc) { [unowned self](images) in
                if images != nil && images!.count > 0 {
                    self.submitAvatar(images: images!)
                }
            }
            
        }
    }
    
    //提交头像
    func submitAvatar(images: [UIImage]) {
        
        var imageupLoadModel: ImageUploadModel?
        
        WWBeginLoadingWithStatus("开始提交")
        
        let dispatchGroup = DispatchGroup()
        
        dispatchGroup.enter()
        ImageUploadModel.commitImage(images) { (response) in
            if response.success {
                if let arr = response.value, arr.count > 0 {
                    imageupLoadModel = arr[0]
                }
                else {
                    WWError("上传图片出错")
                }
            }
            else {
                WWError("上传图片出错")
            }
            
            dispatchGroup.leave()
        }
        
        dispatchGroup.notify(queue: DispatchQueue.main) { 
            guard imageupLoadModel != nil, let urlPath = imageupLoadModel!.url else{
                return
            }
            
            ImageUploadModel.commitAvatarData(urlPath, completionHandler: { (response) in
                if response.success {
                    
                    self.avatarImageView.image = images[0]
                    WWSuccess("提交成功")
                    
                    if let handler = self.avatarChangeHandler {
                        handler()
                    }
                }
                else {
                    WWError(response.message)
                }
            })
        }
    }
    
    func bind(_ model: UserInfoModel) {
        
        self.avatarImageView.kf.setImage(with: URL.init(string: ImageUrlPrefix + (model.avatarUrl ?? "")), placeholder: UIImage.init(named: "scene_touxiang"), options: nil, progressBlock: nil, completionHandler: nil)
        self.usernameLabel.text = model.username ?? "未获取"
    }
}
